package omq.panel;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import omq.api.OMQConnectionFactory;
import omq.api.OMQConnectionSOAP;
import omq.api.OMQMessage;
import omq.api.OMQQueue;
import omq.api.OMQQueueManager;
import omq.api.logger.OMQLogger;
import omq.file.OMQFile;
import omq.screen.OmqTesterMainScreen;

import component.OmqButton;

import constant.OmqTesterClientConst;

public class PeekMsgPanel extends OmqPanel {

	boolean fixbug = false;

	/**
	 * 
	 * 
	 */
	private static final long serialVersionUID = -4200294446762101443L;

	private JLabel responseLbl;
	private OmqButton peekBtn;
	
	
	public PeekMsgPanel(LayoutManager arg0, boolean arg1) {
		super(arg0, arg1);
		initialize();
	}

	public PeekMsgPanel(LayoutManager arg0) {
		super(arg0);
		initialize();
	}

	public PeekMsgPanel(boolean arg0) {
		super(arg0);
		initialize();
	}

	public PeekMsgPanel() {
		super();
		initialize();
	}
	
	private void initialize(){
		setLayout(new GridBagLayout());
		getInfoLbl().setText("<html><body>" + getTitle("Peek message") + "<br><p style='padding-left:25px;padding-bottom:3px'>Use this method to peek at a message from a queue without deleting it.<br><br>'Peek message' is used for browsing the first message on the queue, if you want to delete the message while peeking it use the <span style='font-weight:bold'>Message->Receive</span> function.<br><br></body></html>");
		
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.anchor = GridBagConstraints.LINE_START;
		c.gridx = 0;
		
		c.gridy = 0;
		
		// changing label size
		infoLbl.setPreferredSize(new Dimension(450,150));
		
		add(getInfoLbl(),c);
		
		c.gridy = 1;
		OmqPanel btnPnl = new OmqPanel(new FlowLayout());
		btnPnl.add(getPeekBtn());
		btnPnl.add(new JLabel(""));
		add(btnPnl,c);
		
		
		
		c.gridy = 2;
		add(getResponseLbl(),c);
		
		c.gridy = 3;
		c.weighty = 1.0;
		add(new JLabel(""),c);
		
		initpref();
		
	}

	public OmqButton getPeekBtn() {
		if(peekBtn == null){
			peekBtn = new OmqButton("Peek");
			peekBtn.addActionListener(new ActionListener() {
			
				public void actionPerformed(ActionEvent arg0) {

					OMQLogger.getInstance().info("peek message request is launched");

					 HashMap pref = OmqTesterMainScreen.prefMap;
						
					 // hagai : cleaning text on bottom of the screen when
					// peek a few messages in a row...
					
					 if (fixbug) {
						String emptyResponse;

						emptyResponse = "<html><body><center><hr><h2 style='color:"
								+ OmqTesterClientConst.GUIResponseOKcolor
								+ ";font-size:10px;text-decoration:underline;Font-name: arial;width:450px;'></h2><bR>";
						emptyResponse += "<p align='center' style='padding-left:40px;Font-name: arial;'>";
						emptyResponse += "";
//						emptyResponse += "wait while peek message...";
						emptyResponse += "</p></body></html>";

						getResponseLbl().setText(emptyResponse);
					}
					 
						JOptionPane.showMessageDialog(new JFrame(),"<html><body>Peeking message, please wait ...</body></html>","Message",JOptionPane.INFORMATION_MESSAGE);
					 waitForInfo(true);
					 OMQMessage msg = null;
					 String response = null;
					try {
						
						conn = OMQConnectionFactory.getConnection(myPreferences.get(OmqTesterClientConst.PREF_USER_NAME, OmqTesterClientConst.PREF_USER_NAME),
								myPreferences.get(OmqTesterClientConst.PREF_PASSWORD, OmqTesterClientConst.PREF_PASSWORD),
								myPreferences.get(OmqTesterClientConst.PREF_SERVER_URL, OmqTesterClientConst.PREF_SERVER_URL),
								new OMQQueueManager(myPreferences.get(OmqTesterClientConst.PREF_QUEUE_MGR, OmqTesterClientConst.PREF_QUEUE_MGR)));

						OMQLogger.getInstance().info("user      = "+myPreferences.get(OmqTesterClientConst.PREF_USER_NAME, OmqTesterClientConst.PREF_USER_NAME));						
						OMQLogger.getInstance().info("qmgr      = "+myPreferences.get(OmqTesterClientConst.PREF_QUEUE_MGR,OmqTesterClientConst.PREF_QUEUE_MGR));						
						OMQLogger.getInstance().info("queue     = "+myPreferences.get(OmqTesterClientConst.PREF_QUEUE_NAME,OmqTesterClientConst.PREF_QUEUE_NAME));						
						OMQLogger.getInstance().info("server    = "+myPreferences.get(OmqTesterClientConst.PREF_SERVER_URL,OmqTesterClientConst.PREF_SERVER_URL));

						sess = conn.createSession(false);
											
						OMQLogger.getInstance().info("about to peek a message, please wait");

						msg = sess.peekMessage(new OMQQueue(myPreferences.get(OmqTesterClientConst.PREF_QUEUE_NAME,OmqTesterClientConst.PREF_QUEUE_NAME)));
						
					} catch (Exception e) {
						OMQLogger.getInstance().error(e.getMessage());
						JOptionPane.showMessageDialog(new JFrame(),"<html><body>" + e.getMessage() + "</body></html>","System error",JOptionPane.ERROR_MESSAGE);
						response = "<html><body><center><center><hr><h2 style='color:"+OmqTesterClientConst.GUIResponseFailedcolor+";font-size:10px;text-decoration:underline;Font-name: arial;width:450px;'>Connection check failed</h2><br>" + responseMsg;
						getResponseLbl().setText(response);
						waitForInfo(false);
					}
					 if((msg != null) && (sess.getLastErrorCode() == 0))
					 {
						OMQLogger.getInstance().info("message peek succesfully, msgid = "+sess.getLastMessageID());

						 OMQLogger.getInstance().info("about to examine message content");
						 
						// handle File message
						 try
						 {
							OMQLogger.getInstance().info("trying to convert message to java object");

							 Object obj = msg.getMsgBodyAsObject();
							 if (obj instanceof OMQFile) 
							 {
									String filenamePrefix = "c:\\temp\\"+"MsgID-"+msg.getMsgID()+"__";
									
									OMQFile fileMessage = (OMQFile) obj;
									OMQLogger.getInstance().info("got OMQ-File message from queue");
									OMQLogger.getInstance().info("file name is "+fileMessage.getOmqFileName());
									String currFilename = fileMessage.getOmqFileName();
												
									currFilename = filenamePrefix+currFilename;
									OMQLogger.getInstance().info("new file name will be "+currFilename);
									
									File file = new File(currFilename);
									FileOutputStream fileOutputStream = new FileOutputStream(file);	
								
									OMQLogger.getInstance().info("about to write "+currFilename);
									
									fileOutputStream.write(fileMessage.getOmqFileContent());
									fileOutputStream.flush();
									fileOutputStream.close();
									
									
								 response = "<html><body><center><hr><h2 style='color:"+OmqTesterClientConst.GUIResponseOKcolor+";font-size:10px;text-decoration:underline;Font-name: arial;width:450px;'>Message peek successful</h2><bR>";
								 response += "<p align='left' style='padding-left:40px;Font-name: arial;'>message id&nbsp;&nbsp;&nbsp;&nbsp;: " + msg.getMsgID();
								 response += "<br>content&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: "; 
								 response += "Message content is a file - it is saved on "+currFilename;
								 response += "</p></body></html>";								
							 }
							 // if message type is String Object 
							 // (here for historical reasons, we used to send text as Java String)
							 else if (obj instanceof String)
							 {
								 // we print it to the screen
								 String PeekedMsg = (String)obj;
								
								 OMQLogger.getInstance().info("got Text-String message from queue : "+PeekedMsg);

								 response = "<html><body><center><hr><h2 style='color:"+OmqTesterClientConst.GUIResponseOKcolor+";font-size:10px;text-decoration:underline;Font-name: arial;width:450px;'>Message peek successful</h2><bR>";
								 response += "<p align='left' style='padding-left:40px;Font-name: arial;'>message id&nbsp;&nbsp;&nbsp;&nbsp;: " + msg.getMsgID();
								 response += "<br>content&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: "; 
								 response += "Message content is a text (String) : "+PeekedMsg;
								 response += "</p></body></html>";		
							 }

						 }
						 // message is not String or OMQFile
						 catch (Exception e)
						 {
						// message is not a java object
							 
							 // if message type is other - we just print it to the screen
							 
							OMQLogger.getInstance().info("message type it Other - printing it to screen");

							 if (msg.getMsgType().getBodyType().compareToIgnoreCase("other") == 0)
							 {
								 // when message type is Other - we print it to the screen
									 String PeekedMsg = "";
									try {
										PeekedMsg = new String(msg.getMsgBodyasByteArray(),"UTF-8");
									} catch (UnsupportedEncodingException e1) {
										// TODO Auto-generated catch block
										OMQLogger.getInstance().info("unable to convert byte-array to UTF-8 - displaying it in default encoding");
										PeekedMsg = new String(msg.getMsgBodyasByteArray());
									}
									
									OMQLogger.getInstance().info("got Text-String message from queue : "+PeekedMsg);

									 response = "<html><body><center><hr><h2 style='color:"+OmqTesterClientConst.GUIResponseOKcolor+";font-size:10px;text-decoration:underline;Font-name: arial;width:450px;'>Message peek successful</h2><bR>";
									 response += "<p align='left' style='padding-left:40px;Font-name: arial;'>message id&nbsp;&nbsp;&nbsp;&nbsp;: " + msg.getMsgID();
									 response += "<br>content&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: "; 
									 response += "Message content is a text (String) : "+PeekedMsg;
									 response += "</p></body></html>";								 
							 }
							 else
							 {
								// when message type is not Other - we save it to a file with the type extension
								OMQLogger.getInstance().info("message type is not Other - saving it to file");
								
								String msgType = msg.getMsgType().getBodyType();
//								String msgEncoding = msg.getMsgEncoding().getBodyEncoding();
								String filenamePrefix = "c:\\temp\\";
								String unknownFilename = "unknownSource";
								String suffix = msg.getMsgType().getBodyType().toLowerCase();
//								String suffix = "txt";
//								if (msg.getMsgType().getBodyType().compareToIgnoreCase("CSV") == 0)
//								{
//									suffix="csv";
//								}
//								if (msg.getMsgType().getBodyType().compareToIgnoreCase("XML") == 0)
//								{
//									suffix="xml";
//								}
								
								String currFilename = filenamePrefix+"MsgID-"+msg.getMsgID()+"."+unknownFilename+"."+suffix;
								
								OMQLogger.getInstance().info("message body type is "+msgType );
//								OmqLogger.getInstance().info("message body encoding is "+msgEncoding );
								
								File file = new File(currFilename);
								FileOutputStream fileOutputStream;
								try 
								{

									OMQLogger.getInstance().info("message not originated from Client Tester, about to write message to file "+currFilename);
									fileOutputStream = new FileOutputStream(file);
									fileOutputStream.write(msg.getMsgBodyasByteArray());
									
									fileOutputStream.flush();
									fileOutputStream.close();
									
									 response = "<html><body><center><hr><h2 style='color:"+OmqTesterClientConst.GUIResponseOKcolor+";font-size:10px;text-decoration:underline;Font-name: arial;width:450px;'>Message peek successful</h2><bR>";
									 response += "<p align='left' style='padding-left:40px;Font-name: arial;'>message id&nbsp;&nbsp;&nbsp;&nbsp;: " + msg.getMsgID();
									 response += "<br>content&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: "; 
									 response += "message not originated from Client Tester - it is saved at "+currFilename;
									 response += "</p></body></html>";
									 
								} catch (Exception e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}	
								
							 }
						 }
						 
					 }else {
						OMQLogger.getInstance().info("peek message failed, rc = "+sess.getLastErrorCode()+" error description = "+sess.getLastErrorDescription());
						 response = printErrorFromOMQ("Peek message",true);
					 }
					 waitForInfo(false);
					 getResponseLbl().setText(response);
					 fixbug = true;
				}
			});
		}
		return peekBtn;
	}

	public JLabel getResponseLbl() {
		if(responseLbl == null){
			responseLbl = new JLabel("");
		}
		return responseLbl;
	}

	public void resetPanel(){
		getResponseLbl().setText("");
	}
}
